package com.example.servlet;

import com.example.model.User;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin-order")
public class AdminOrderServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        // 检查是否是管理员
        if (currentUser == null || !"admin".equals(currentUser.getUsername())) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT o.*, u.username, b.name as book_title FROM orders o LEFT JOIN users u ON o.user_id = u.id LEFT JOIN books b ON o.book_id = b.id ORDER BY o.order_time DESC";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            
            List<Map<String, Object>> orders = new ArrayList<>();
            while (rs.next()) {
                Map<String, Object> order = new HashMap<>();
                order.put("id", rs.getInt("id"));
                order.put("userId", rs.getInt("user_id"));
                order.put("bookId", rs.getInt("book_id"));
                order.put("quantity", rs.getInt("quantity"));
                order.put("totalPrice", rs.getDouble("total_price"));
                order.put("orderTime", rs.getTimestamp("order_time"));
                order.put("status", rs.getString("status"));
                order.put("username", rs.getString("username"));
                order.put("bookTitle", rs.getString("book_title"));
                orders.add(order);
            }
            
            request.setAttribute("orders", orders);
            request.getRequestDispatcher("admin-order.jsp").forward(request, response);
            
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库连接错误: " + e.getMessage());
            request.getRequestDispatcher("admin-order.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
} 